//
//  CentralViewController.m
//  BlueToothPeripheral
//
//  Created by US bike on 2017/8/4.
//  Copyright © 2017年 US bike. All rights reserved.
//

#import "CentralViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "Tools.h"



@interface CentralViewController ()<CBCentralManagerDelegate,CBPeripheralDelegate>

@property (weak, nonatomic) IBOutlet UITextField *senderTextField;
@property (weak, nonatomic) IBOutlet UILabel *readLbl;
@property (weak, nonatomic) IBOutlet UILabel *notifyLbl;

@property (weak, nonatomic) IBOutlet UIButton *connectBtn;
@property (weak, nonatomic) IBOutlet UITextView *logTextView;


@property (strong, nonatomic) CBCentralManager *centralManager;
@property (strong, nonatomic) CBPeripheral *selectedPeripheral;

@property (strong, nonatomic) CBCharacteristic *subscriptCharacteristic;
@property (strong, nonatomic) CBCharacteristic *writeCharacteristic;
@property (strong, nonatomic) CBCharacteristic *readCharacteristic;

@end

@implementation CentralViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenAction)];
    [self.view addGestureRecognizer:tap];
}

//初始化界面
- (void) setupUI {
    
    self.senderTextField.text = @"我是蓝牙中心设备要发送的数据";
}


#pragma mark CBCentralManagerDelegate
//本地蓝牙设备的状态发生变化
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    switch (central.state) {
        case CBCentralManagerStateUnknown:   //CB中央管理器启动状态
            NSLog(@"本地蓝牙状态，初始的时候是未知的（刚刚创建的时候）");
            break;
        case CBCentralManagerStateResetting:
            NSLog(@"本地蓝牙状态，正在重置状态");
            break;
        case CBCentralManagerStateUnsupported:
            NSLog(@"本地蓝牙状态，设备不支持的状态");
            break;
        case CBCentralManagerStateUnauthorized:
            NSLog(@"本地蓝牙状态，设备未授权状态");
            break;
        case CBCentralManagerStatePoweredOff:
            NSLog(@"本地蓝牙状态，设备关闭状态");
            break;
        case CBCentralManagerStatePoweredOn:
            NSLog(@"本地蓝牙状态，设备开启状态 -- 可用状态");
            //[self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:SERVICE_UUID]] options:nil];
            [self.centralManager scanForPeripheralsWithServices:nil options:nil];
            break;
        default:
            break;
    }
}

- (void)centralManager:(CBCentralManager *)central willRestoreState:(NSDictionary<NSString *, id> *)dict {
    
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *, id> *)advertisementData RSSI:(NSNumber *)RSSI {
    
    NSLog(@"发现蓝牙设备：name = %@  UUID = %@", peripheral.name, peripheral.identifier.UUIDString);
    
    //发现蓝牙设备
    if ([peripheral.name isEqualToString:BLUETOOTH_NAME]) {
        NSLog(@"发现指定蓝牙设备");
        
        peripheral.delegate = self;
        self.selectedPeripheral = peripheral;
        
        [self.centralManager connectPeripheral:peripheral options:nil];
        [self.centralManager stopScan];
    }

}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    NSLog(@"蓝牙已经连接到外设,开始查找指定的service,UUID : %@", SERVICE_UUID);

    //[peripheral discoverServices:nil];
    [peripheral discoverServices:@[[CBUUID UUIDWithString:SERVICE_UUID]]];
    
}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error {
    NSLog(@"连接外设失败，%@",error);
    
}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error {
    
    NSLog(@"与外设断开连接，%@",error);
    
}


#pragma mark CBPeripheralDelegate

- (void)peripheralDidUpdateName:(CBPeripheral *)peripheral {
    
    
}

- (void)peripheral:(CBPeripheral *)peripheral didModifyServices:(NSArray<CBService *> *)invalidatedServices  {
    
}

- (void)peripheralDidUpdateRSSI:(CBPeripheral *)peripheral error:(nullable NSError *)error {
    
}

- (void)peripheral:(CBPeripheral *)peripheral didReadRSSI:(NSNumber *)RSSI error:(nullable NSError *)error {
    
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(nullable NSError *)error {
    if (!error) {
        NSLog(@"成功发现服务，开始查找特征");
        for (CBService *service in peripheral.services) {
            
            [peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:CHARACTERISTIC_UUID_READ],[CBUUID UUIDWithString:CHARACTERISTIC_UUID_WRITE],[CBUUID UUIDWithString:CHARACTERISTIC_UUID_SUBSCRIPT]] forService:service];
        }
    } else {
        NSLog(@"发现服务失败,%@",error);
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverIncludedServicesForService:(CBService *)service error:(nullable NSError *)error {
    if (!error) {
        NSLog(@"发现指定服务");
        if ([service.UUID.UUIDString isEqualToString:SERVICE_UUID]) {
            [peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:CHARACTERISTIC_UUID_READ],[CBUUID UUIDWithString:CHARACTERISTIC_UUID_WRITE]] forService:service];
        }
        
    } else {
        NSLog(@"发现指定服务失败,%@",error);
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(nullable NSError *)error {
    if (!error) {
        NSLog(@"成功发现特征");
        
        for (CBCharacteristic *characteristic in service.characteristics) {//写类型
            NSLog(@"特征 UUID = %@",characteristic.UUID);
            if ([characteristic.UUID.UUIDString isEqualToString:CHARACTERISTIC_UUID_WRITE]) {
                self.writeCharacteristic = characteristic;
            } else if ([characteristic.UUID.UUIDString isEqualToString:CHARACTERISTIC_UUID_SUBSCRIPT]) {//订阅类型
                [peripheral setNotifyValue:YES forCharacteristic:characteristic];
                self.subscriptCharacteristic = characteristic;
            } else if ([characteristic.UUID.UUIDString isEqualToString:CHARACTERISTIC_UUID_READ]) {
                self.readCharacteristic = characteristic;
            }
        }
        
    } else {
        NSLog(@"发现特征失败,%@",error);
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error {
    NSLog(@"收到新的信息， 读消息或订阅消息都从这里获取");
    
    
    if (!error) {
        if ([characteristic.UUID.UUIDString isEqualToString:CHARACTERISTIC_UUID_READ]) {
            NSLog(@"收到读取的消息");
            NSString *str = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
            self.readLbl.text = str;
            
            
        } else if ([characteristic.UUID.UUIDString isEqualToString:CHARACTERISTIC_UUID_SUBSCRIPT]) {
            NSLog(@"收到订阅的消息");
            NSString *str = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
            self.notifyLbl.text = str;
        }
    } else {
        NSLog(@"收到消息时发生错误,%@",error);
    }
    
}

- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error {
    NSLog(@"写数据回调");
    if (!error) {
        NSLog(@"成功写入数据 到特征 UUID = %@",characteristic.UUID);
        
    } else {
        NSLog(@"订阅状态发生变化回调发生错误,%@",error);
    }
    
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error {
    NSLog(@"订阅状态发生变化");
    if (!error) {
        if (characteristic.isNotifying) {
            NSLog(@"开始订阅特征 UUID = %@",characteristic.UUID);
        } else {
            NSLog(@"取消订阅特征 UUID = %@",characteristic.UUID);
            
        }
    } else {
        NSLog(@"订阅状态发生变化回调发生错误,%@",error);
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error {
    
}

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(nullable NSError *)error {
    
}

- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForDescriptor:(CBDescriptor *)descriptor error:(nullable NSError *)error {
    
}


#pragma mark 点击事件

- (IBAction)sendAction:(id)sender {
    NSData *data = [self.senderTextField.text dataUsingEncoding:NSUTF8StringEncoding];
    [self.selectedPeripheral writeValue:data forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithoutResponse];
}

- (IBAction)readAction:(id)sender {
    [self.selectedPeripheral readValueForCharacteristic:self.readCharacteristic];
}


- (IBAction)connectAction:(UIButton *)sender {
    if (!self.centralManager) {
        self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
        [sender setTitle:@"正在连接" forState:UIControlStateNormal];
    } else {
        [self cancelConnection];
        [sender setTitle:@"开始连接" forState:UIControlStateNormal];

    }
    
}




- (void) hiddenAction {
    [self.view endEditing:YES];
}


- (void) cancelConnection {
    if ([self.centralManager isScanning]) {
        [self.centralManager stopScan];
    }
    
    if (self.selectedPeripheral) {
        [self.centralManager cancelPeripheralConnection:self.selectedPeripheral];
    }
    self.selectedPeripheral = nil;
    self.centralManager = nil;
}

- (void) dealloc {
    [self cancelConnection];
}

@end
